package com.fernfx.xingtan.main.presenter;

import android.text.TextUtils;

import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.AppManager;
import com.fernfx.xingtan.common.base.BaseActivity;
import com.fernfx.xingtan.common.base.BaseEntity;
import com.fernfx.xingtan.common.network.IRequestCallback;
import com.fernfx.xingtan.common.network.entity.NetworkOKResult;
import com.fernfx.xingtan.main.contract.MyContract;
import com.fernfx.xingtan.main.entity.MyUserInfoEntity;
import com.fernfx.xingtan.main.model.MyModel;
import com.fernfx.xingtan.utils.FastJsonUtil;
import com.fernfx.xingtan.utils.OtherUtil;
import com.fernfx.xingtan.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

/**
 * Created by admin on 2018/8/15.
 * 我的功能presenter
 */

public class MyPresenter<P extends MyContract.View> implements MyContract.Presenter {
    private P P;
    private MyContract.Model model;

    @Override
    public void init(MyContract.View view) {
        this.P = (P)view;
        this.model = new MyModel();
    }

    @Override
    public void getUserInfo(Map<String,Object> requestArgsMap){
       //显示加载框
        final BaseActivity baseActivity = (BaseActivity)AppManager.getAppManager().currentActivity();

        model.getUserInfo(requestArgsMap, new IRequestCallback() {
            @Override
            public void onSuccessful(NetworkOKResult result) {
                String message = result.getMessage();
                if (TextUtils.isEmpty(message)) {
                    onNetworkError(result.getMessage(),500);
                    return;
                }
                //获取用户信息成功后并展示
                MyUserInfoEntity userInfoEntity = FastJsonUtil.fromBean(message, MyUserInfoEntity.class);
                if (null != userInfoEntity && OtherUtil.checkRequestStatus(userInfoEntity.getSuccess(),userInfoEntity.getStatus())) {
//                    P.showUserInfo(userInfoEntity);
                    EventBus.getDefault().post(userInfoEntity);
                }else {
                    ToastUtil.showCentertoast(userInfoEntity.getMsg());
                }
            }

            @Override
            public void onFailure(String errorMessage, int errorCode) {
                baseActivity.hideLoading();
                if (TextUtils.isEmpty(errorMessage)) {
                    onNetworkError(errorMessage,errorCode);
                    return;
                }

                final BaseEntity baseEntity = FastJsonUtil.fromBean(errorMessage, BaseEntity.class);
                if (null != baseEntity && !TextUtils.isEmpty(baseEntity.getMsg())){
                    ToastUtil.showCentertoast(baseEntity.getMsg());
                }
            }

            @Override
            public void onNetworkError(String errorMessage, int errorCode) {
                baseActivity.hideLoading();
                ToastUtil.showCentertoast(R.string.network_error);
            }
        });
    }
}
